package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.RecentlyViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.FFUtils;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.ReadHistoryResponse;
import com.jjwxc.jwjskandriod.model.ScreenResponse;
import com.jjwxc.jwjskandriod.model.VipDistanceResponse;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.bean.CollBookBean;
import com.jjwxc.jwjskandriod.widget.GroupPop;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;

import java.util.ArrayList;
import java.util.List;

public class RecentlyFragment extends Fragment {
    private String value;
    private String key;
    private View view;
    private RecyclerView rv_recently;
    private RecentlyAdapter adapter;

    public static long lastRefreshTime;
    private XRefreshView refreshView;
    private int page = 0;
    ScreenResponse screenResponse = new ScreenResponse();

    public RecentlyFragment(String key, String value) {
        this.key = key;
        this.value = value;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_recently, container, false);
            setViewId();
            setListener();
            //获取用户是不是VIP
            getVipDistance();
        }
        afterCreate(0);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListener() {
        rv_recently.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new RecentlyAdapter(getActivity());
        rv_recently.setAdapter(adapter);
        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(getActivity()));
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);
        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                afterCreate(0);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                afterCreate(page * 10);
            }
        });

    }

    public void setViewId() {
        refreshView = view.findViewById(R.id.recently_view);
        rv_recently = view.findViewById(R.id.rv_recently);
        rv_recently.setNestedScrollingEnabled(false);
        rv_recently.setFocusable(false);
        rv_recently.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_recently.addItemDecoration(new LinearLayouDecoration(getActivity(),
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));

    }

    public void afterCreate(final int page) {
        if (page == 0) {
            refreshView.setLoadComplete(false);
        }
        screenResponse.setIsChildMode(PreUtils.getBoolean("QING_switch", false));
        screenResponse.setLimit(10);
        screenResponse.setOffset(page);
        ((FFActivity) getActivity()).post(Url.listReadingHistory, null, ReadHistoryResponse.class, new FFNetWorkCallBack<ReadHistoryResponse>() {
            @Override
            public void onSuccess(ReadHistoryResponse response) {
                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() < 10) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.stopRefresh();
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }


                }

            }

            @Override
            public boolean onFail(ReadHistoryResponse response) {
                return false;
            }
        }, JSON.toJSONString(screenResponse));

    }

    public String getScreenResponse() {

        return JSON.toJSONString(screenResponse);
    }

    public void setScreenResponse(String screen) {
        ScreenResponse response = JSON.parseObject(screen, ScreenResponse.class);
        page = 0;
        screenResponse.setBookType(response.getBookType());
        screenResponse.setSortType(response.getSortType());
        screenResponse.setSubscribeStatus(response.getSubscribeStatus());
        screenResponse.setReadingRate(response.getReadingRate());
        screenResponse.setCollectStatus(response.getCollectStatus());
        screenResponse.setIsChildMode(PreUtils.getBoolean("QING_switch", false));
        //刷新数据
        afterCreate(0);
    }

    public class RecentlyAdapter extends BaseRecyclerAdapter<RecentlyViewHolder> {
        private Context context;


        private List<ReadHistoryResponse.DataBean> mData = new ArrayList<>();


        public RecentlyAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<ReadHistoryResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<ReadHistoryResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public RecentlyViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.recently_item_fragment, parent, false);
            RecentlyViewHolder viewHolder_text = new RecentlyViewHolder(mView);
            return viewHolder_text;

        }

        @Override
        public RecentlyViewHolder getViewHolder(View view) {
            return new RecentlyViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @Override
        public void onBindViewHolder(final RecentlyViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {

            holder.tv_title.setText(mData.get(position).getBookInfo().getName());
            holder.tv_time.setText(FFUtils.stringToDateRecent(mData.get(position).getTime()));
            FFImageLoader.loadImage(getContext(), holder.img_recently_item, mData.get(position).getBookInfo().getCoverImgUrl(), mData.get(position).getBookInfo().getBookId(), true);
            if (mData.get(position).isIsInBookCase()) {
                holder.ll_recently.setBackgroundResource(R.drawable.collect_law_false);
                holder.img_fag.setImageResource(R.mipmap.jianshao_icon);
            } else {
                holder.ll_recently.setBackgroundResource(R.drawable.collect_law_true);
                holder.img_fag.setImageResource(R.mipmap.add_icon);
            }
            holder.ll_recently.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.get(position).isIsInBookCase()) {
                        FFApplication.showToast("已收藏");
                        return;
                    }
                    GroupPop.collentGroupPop(v, getActivity(), group -> {
                        if (group == null) {
                            return;
                        }
                        ((FFActivity) getActivity()).post(Url.addBookcase, null, String.class, new FFNetWorkCallBack<String>() {
                            @Override
                            public void onSuccess(String response) {
                                if (response.contains("200")) {
                                    mData.get(position).setIsInBookCase(true);
                                    holder.ll_recently.setBackgroundResource(R.drawable.collect_law_false);
                                    holder.img_fag.setImageResource(R.mipmap.jianshao_icon);
                                    notifyItemChanged(position);
                                    FFApplication.showToast("收藏成功");
                                }
                            }

                            @Override
                            public boolean onFail(String response) {
                                return false;
                            }
                        }, "{\"bookId\":\"" + mData.get(position).getBookInfo().getBookId() + "\",\"bookcaseGroupId\":\"" + group + "\"}");

                    });


                }
            });
            holder.cl_recently_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.get(position) != null) {
                        new FFNetWork().post(Url.vipDistance, null, new FFNetWorkCallBack<VipDistanceResponse>() {
                            @Override
                            public void onSuccess(VipDistanceResponse response) {
                                if (response.getCode() == 200) {
                                    ReadActivity.userIsVip = response.getData() <= 0;
                                }
                            }

                            @Override
                            public boolean onFail(VipDistanceResponse response) {
                                return false;
                            }
                        }, VipDistanceResponse.class);
                        CollBookBean collBookBean = new CollBookBean();
                        collBookBean.set_id(mData.get(position).getBookInfo().getBookId());
                        collBookBean.setAuthor(mData.get(position).getBookInfo().getAuthor());
                        collBookBean.setTitle(mData.get(position).getBookInfo().getName());
                        collBookBean.setShortIntro(StUtils.reBlank(mData.get(position).getBookInfo().getBookIntro()));
                        collBookBean.setCover(mData.get(position).getBookInfo().getCoverImgUrl());
                        collBookBean.setIsUpdate(true);
                        collBookBean.setMonthSubscribe(mData.get(position).getBookInfo().isIsMonthSubscribe());
                        Intent intent = new Intent(getActivity(), ReadActivity.class);
                        intent.putExtra(ReadActivity.EXTRA_COLL_BOOK, collBookBean);
                        intent.putExtra(ReadActivity.EXTRA_IS_COLLECTED, true);
                        startActivity(intent);
                    }
                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }
    public void getVipDistance() {
        new FFNetWork().post(Url.vipDistance, null, new FFNetWorkCallBack<VipDistanceResponse>() {
            @Override
            public void onSuccess(VipDistanceResponse response) {
                if (response.getCode() == 200) {
                    ReadActivity.userIsVip = response.getData() <= 0;
                }
            }

            @Override
            public boolean onFail(VipDistanceResponse response) {
                return false;
            }
        }, VipDistanceResponse.class);
    }
}
